#!/usr/bin/perl
# 
# Exercise 8.11
# 
# Write a subroutine that takes as arguments an amino acid; a position 1, 2, or 3; and 
# a nucleotide. It then takes each codon that encodes the specified amino acid (there 
# may be from one to six such codons), and mutates it at the specified position to the 
# specified nucleotide. Finally, it returns the set of amino acids that are encoded by 
# the mutated codons.
#
# Answer for Exercise 8.11

use strict;
use warnings;
use BeginPerlBioinfo;

print "Give a one-character amino acid: ";
my $aa = <STDIN>;
chomp $aa;

print "Give a position 1,2, or 3: ";
my $position = <STDIN>;
chomp $position;

print "Give a nucleotide: ";
my $nucleotide = <STDIN>;
chomp $nucleotide;

print "Here is the set of amino acids that may result from mutating\n";
print "a codon for amino acid $aa at position $position to nucleotide $nucleotide:\n";

my @set_of_aa = aa2mutated_aa($aa, $position, $nucleotide);

print "@set_of_aa\n";

exit;

##################################################
# Subroutines
##################################################

sub aa2mutated_aa {

	my($aa,$position,$nucleotide) = @_;

	my(%reverse_genetic_code) = (
	
	'A' => 'GCA GCC GCG GCT',		# Alanine
	'C' => 'TGC TGT',			# Cysteine
	'D' => 'GAC GAT',			# Aspartic Acid
	'E' => 'GAA GAG',			# Glutamic Acid
	'F' => 'TTC TTT',			# Phenylalanine
	'G' => 'GGA GGC GGG GGT',		# Glycine
	'H' => 'CAC CAT',			# Histidine
	'I' => 'ATA ATC ATT',			# Isoleucine
	'K' => 'AAA AAG',			# Lysine
	'L' => 'CTA CTC CTG CTT TTA TTG',	# Leucine
	'M' => 'ATG',				# Methionine
	'N' => 'AAC AAT',			# Asparagine
	'P' => 'CCA CCC CCG CCT',		# Proline
	'Q' => 'CAA CAG',			# Glutamine
	'R' => 'CGA CGC CGG CGT AGA AGG',	# Arginine
	'S' =>'TCA TCC TCG TCT AGC AGT',	# Serine
	'T' => 'ACA ACC ACG ACT',		# Threonine
	'V' => 'GTA GTC GTG GTT',		# Valine
	'W' => 'TGG',				# Tryptophan
	'Y' => 'TAC TAT',			# Tyrosine
	'_' => 'TAA TAG TGA',			# Stop
	);

	my %mutated_aa = ();

	my @codons = split(' ', $reverse_genetic_code{$aa});

	foreach my $codon (@codons) {

		# mutate the codon at the desired position and with the desired nucleotide
		# (we have to subtract one from the position because 
		# positions in strings are numbered starting from 0
		substr($codon, $position-1, 1) = $nucleotide;

		my $new_aa = codon2aa($codon);

		$mutated_aa{$new_aa}++;
	}

	return keys %mutated_aa;
}
